package org.xyl.context;

import java.util.*;
import org.xyl.context.BusinessEntityContext.*;

/**
 * 业务实体上下文提供器 - 负责获取业务实体相关信息
 */
public class BusinessEntityContextProvider {
    
    /**
     * 获取业务实体上下文
     * 这里模拟从数据库或API获取数据，实际实现需要连接真实数据源
     */
    public BusinessEntityContext getBusinessEntityContext(Map<String, List<String>> entities) {
        BusinessEntityContext context = new BusinessEntityContext();
        
        // 处理设备信息
        if (entities.containsKey(EntityRecognizer.ENTITY_DEVICE_ID)) {
            List<String> deviceIds = entities.get(EntityRecognizer.ENTITY_DEVICE_ID);
            for (String deviceId : deviceIds) {
                // 模拟获取设备信息
                Device device = getDeviceById(deviceId);
                if (device != null) {
                    context.addDevice(device);
                    
                    // 根据设备关联客户
                    Customer customer = getCustomerById(device.getCustomerId());
                    if (customer != null) {
                        context.addCustomer(customer);
                    }
                    
                    // 获取设备的历史工单
                    List<WorkOrder> workOrders = getWorkOrdersByDeviceId(deviceId);
                    for (WorkOrder order : workOrders) {
                        context.addWorkOrder(order);
                    }
                    
                    // 获取设备的最新告警
                    List<Alert> alerts = getRecentAlertsByDeviceId(deviceId);
                    for (Alert alert : alerts) {
                        context.addAlert(alert);
                    }
                }
            }
        }
        
        return context;
    }
    
    // 模拟获取设备信息
    private Device getDeviceById(String deviceId) {
        // 这里返回模拟数据，实际应该从数据库或API获取
        if ("A123".equals(deviceId)) {
            return new Device("A123", "ESL-202", "V1.5", "CUST001");
        }
        return new Device(deviceId, "Unknown", "Unknown", null);
    }
    
    // 模拟获取客户信息
    private Customer getCustomerById(String customerId) {
        if ("CUST001".equals(customerId)) {
            return new Customer("CUST001", "上海XX超市", "contact@example.com");
        }
        return null;
    }
    
    // 模拟获取工单信息
    private List<WorkOrder> getWorkOrdersByDeviceId(String deviceId) {
        List<WorkOrder> orders = new ArrayList<>();
        if ("A123".equals(deviceId)) {
            // 添加一个3个月前的工单
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, -3);
            Date threeMonthsAgo = cal.getTime();
            
            orders.add(new WorkOrder(
                "WO001", deviceId, "CUST001", 
                "信号弱", "已解决", threeMonthsAgo
            ));
        }
        return orders;
    }
    
    // 模拟获取告警信息
    private List<Alert> getRecentAlertsByDeviceId(String deviceId) {
        List<Alert> alerts = new ArrayList<>();
        // 可以根据实际需求添加告警信息
        return alerts;
    }
}